<template>
	<view class="home" @tap="handlePageClick">
		<custom-navbar title="我的预约" :show-back="true" @back="handleBack" />

		<view class="content" :style="{ paddingTop: navBarHeight + 'px' }">
			<!-- 空状态 -->
			<view v-if="isEmpty" class="empty-state fcolcc">
				<image class="empty-image" src="/static/images/common/empty.png"></image>
				<view class="empty-text">暂无预约数据</view>
				<up-button type="primary" shape="circle" @click="loadReservationList(true)"
					style="width: 200rpx;margin-top: 30rpx;">
					重新加载
				</up-button>
			</view>

			<!-- 预约列表 -->
			<view v-else class="reservation-list p30">
				<view class="item mb20" v-for="(item,index) in reservationList" :key="index"
					@click="handledetails(item)">
					<view class="bg">
						<image class="plantbg" :src='item.space_image' mode="aspectFill"></image>
						<view class="top fcc">
							<image class="rentout" :src="cdn('仅出租.svg')"></image>
							<view class="text f22bc99A2E">
								{{item.rent_nature_text}}
							</view>
						</view>
					</view>
					<view class="btm p30">
						<view class="f36bc0 mb18">{{item.space_title}}</view>
						<view class="flex mb30">
							<view class="f245c9 fc">
								<view>租价:</view>
								<view class="FF0C10">{{item.rent_price}}元</view>
							</view>
							<view class="f245c9 fc ml30">
								<view>建筑面积：</view>
								<view class="c398DFB">{{item.building_area}}㎡</view>
							</view>
						</view>
						<!-- 	<view class="f245c9 mb18">预约时间：{{item.reservation_time_text}} {{item.reservation_time_slot}}
						</view> -->
						<up-line></up-line>
						<view class="fcsb mt18">
							<view class="f245c9">地址：{{item.address}}</view>
							<!-- 	<view class="btn f20bcf fcc" :class="{'disabled-btn': item.status !== 0}"
								@click="handleReservation(item)">
								{{item.status === 0 ? '取消预约' : '已'+item.status_text}}
							</view> -->
							<view>
								<view v-if="item.status === 0" class="f24Bc3 FF0C10 fc">
									<image class="wh32" src="/static/images/user/待回复.svg"></image>
									<view class="ml5">待审核</view>
								</view>
								<view v-else-if="item.status === 1" class="f24Bc3 c398DFB fc">
									<image class="wh32" src="/static/images/user/通过.svg"></image>
									<view class="ml5">预约通过</view>
								</view>
								<view v-else-if="item.status === 2" class="reject-container">
									<!-- 触发区域 -->
									<view class="reject-trigger fc f24Bc3 FF0C10" @tap.stop="toggleTooltip(index)">
										<image class="wh32" src="/static/images/user/驳回.svg"></image>
										<view class="ml5">预约驳回</view>
									</view>

									<!-- 自定义Tooltip（关键修改） -->
									<view v-if="activeIndex === index" class="custom-tooltip fc f245c3"
										:style="{ top: tooltipPosition.top + 'px', right: tooltipPosition.right + 'px' }"
										@tap.stop>
										<view class="tooltip-title">驳回原因：</view>
										<view class="tooltip-content">{{ item.reject_reason || '暂无驳回原因' }}</view>
										<view class="tooltip-arrow"></view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="isLoadingMore" class="loading-more fcc">
				<up-loading-icon text='加载中...'></up-loading-icon>
			</view>
			<view v-if="noMoreData" class="no-more fcc">
				没有更多数据了
			</view>
		</view>
	</view>
</template>

<script setup>
	import CustomNavbar from '@/components/custom-navbar.vue'
	import {
		ref,
		onMounted,
		computed,
		onUnmounted,
		getCurrentInstance
	} from 'vue';
	import {
		onReachBottom
	} from '@dcloudio/uni-app'
	import {
		myReservation
	} from '@/api/user'
	// 获取全局cdn方法
	const {
		proxy
	} = getCurrentInstance()
	const cdn = (path) => proxy.$cdn + path
	// 系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)

	// 数据状态
	const isLoading = ref(false)
	const isLoadingMore = ref(false)
	const noMoreData = ref(false)
	const isEmpty = ref(false)

	// 分页参数
	const page = ref(1)
	const limit = ref(10)
	const total = ref(0)

	// 预约列表数据
	const reservationList = ref([])

	// 初始化加载
	onMounted(() => {
		loadReservationList(true)
		uni.$on('pageClick', handlePageClick)
	})
	const activeIndex = ref(null)
	const tooltipPosition = ref({
		top: 0,
		left: 0
	})
	const instance = getCurrentInstance()

	// 修改toggleTooltip方法
	const toggleTooltip = (index) => {
		return new Promise((resolve) => {
			if (activeIndex.value === index) {
				activeIndex.value = null
				return resolve()
			}

			uni.createSelectorQuery()
				.in(instance.proxy)
				.select('.reject-trigger')
				.boundingClientRect((res) => {
					if (!res) return resolve()

					tooltipPosition.value = {
						top: res.bottom + 10,
						left: Math.min(
							res.left - 100,
							uni.getSystemInfoSync().windowWidth - 320 /* tooltip宽度 */
						)
					}
					activeIndex.value = index
					resolve()
				})
				.exec()
		})
	}
	// 点击页面其他区域关闭
	const handlePageClick = () => {
		activeIndex.value = null
	}

	// 微信小程序需要用uni方法监听
	// onMounted(() => {
	// 	uni.$on('clickOutside', handleClickOutside)
	// })

	onUnmounted(() => {
		uni.$off('pageClick', handlePageClick)
	})
	// 加载预约列表
	const loadReservationList = async (isRefresh = false) => {
		if (isLoading.value && !isRefresh) return

		try {
			if (isRefresh) {
				page.value = 1
				noMoreData.value = false
				isLoading.value = true
			} else {
				isLoadingMore.value = true
			}

			const params = {
				page: page.value,
				limit: limit.value
			}

			const res = await myReservation(params)

			if (res.code === 200) {
				if (isRefresh) {
					reservationList.value = res.data.data
					total.value = res.data.total
				} else {
					reservationList.value = [...reservationList.value, ...res.data.data]
				}

				// 检查是否还有更多数据
				if (res.data.data.length < limit.value) {
					noMoreData.value = true
				}

				// 检查空状态
				isEmpty.value = reservationList.value.length === 0
			}
		} catch (error) {
			console.error('加载预约列表失败:', error)
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
			isLoadingMore.value = false
		}
	}

	// 处理预约操作
	const handleReservation = (item) => {
		if (item.status !== 0) return

		uni.showModal({
			title: '提示',
			content: '确定要取消该预约吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						// 这里调用取消预约的接口
						// await cancelReservation(item.space_id)
						uni.showToast({
							title: '取消成功',
							icon: 'success'
						})
						loadReservationList(true)
					} catch (error) {
						console.error('取消预约失败:', error)
						uni.showToast({
							title: '取消失败',
							icon: 'none'
						})
					}
				}
			}
		})
	}

	// 返回
	const handleBack = () => {
		uni.switchTab({
			url: '/pages/user/user'
		})
	}
	const handledetails = (item) => {
		// uni.navigateTo({
		// 	url: `/pages/plant/details`
		// });
		uni.navigateTo({
			url: `/pages/plant/details?space_class=${item.space_class}`
		})
	};
	// 加载更多
	onReachBottom(() => {
		if (isLoadingMore.value || noMoreData.value) return
		page.value += 1
		loadReservationList()
	})
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		min-height: 100vh;
		background-color: #f7f7f7;
		position: relative;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 70rpx);

			.empty-state {
				height: 60vh;
				padding: 40rpx;
				text-align: center;

				.empty-image {
					width: 300rpx;
					height: 300rpx;
					margin-bottom: 30rpx;
				}

				.empty-text {
					font-size: 28rpx;
					color: #999;
				}
			}

			.reservation-list {
				.item {
					background: #FFFFFF;
					border-radius: 20rpx;
					overflow: hidden;

					.bg {
						width: 100%;
						height: 320rpx;
						position: relative;

						.plantbg {
							width: 100%;
							height: 100%;
						}

						.top {
							position: absolute;
							right: 30rpx;
							top: 0;
							flex-direction: column;

							.rentout {
								width: 100rpx;
								height: 94rpx;
							}

							.text {
								position: absolute;
								top: 44rpx;
								color: #99A2E5;
								font-size: 22rpx;
								font-weight: bold;
							}
						}
					}

					.btm {
						.f36bc0 {
							font-size: 36rpx;
							font-weight: bold;
							color: #333;
						}

						.f245c9 {
							font-size: 24rpx;
							color: #5c5c5c;
						}

						.FF0C10 {
							color: #FF0C10;
						}

						.c398DFB {
							color: #398DFB;
						}

						.btn {
							width: 150rpx;
							height: 50rpx;
							background: linear-gradient(90deg, #398DFB 0%, #61DBFF 100%);
							border-radius: 10rpx;
							color: #FFFFFF;

							&.disabled-btn {
								background: #CCCCCC;
							}
						}
					}
				}
			}

			.loading-more,
			.no-more {
				padding: 30rpx 0;
				color: #999;
				font-size: 26rpx;
			}
		}
	}

	.fcolcc {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.fcsb {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.fc {
		display: flex;
		align-items: center;
	}

	.fcc {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.p30 {
		padding: 30rpx;
	}

	.mb18 {
		margin-bottom: 18rpx;
	}

	.mb20 {
		margin-bottom: 20rpx;
	}

	.mb30 {
		margin-bottom: 30rpx;
	}

	.mt18 {
		margin-top: 18rpx;
	}

	.ml30 {
		margin-left: 30rpx;
	}

	/* 关键样式修改 */
	.reject-container {
		position: relative;
		z-index: 1;
		/* 确保在正常文档流 */
	}

	.custom-tooltip {
		position: fixed;
		/* 改为fixed定位 */
		z-index: 9999;
		/* 确保在最顶层 */
		width: 300rpx;
		padding: 20rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 4rpx 15rpx 0rpx rgba(173, 173, 173, 0.3);
		border-radius: 20rpx 0rpx 20rpx 20rpx;
		transform: translateX(-50%);

		/* 箭头样式 */
		.tooltip-arrow {
			position: absolute;
			top: -16rpx;
			left: 50%;
			width: 0;
			height: 0;
			border-left: 10rpx solid transparent;
			border-right: 10rpx solid transparent;
			border-bottom: 10rpx solid #fff;
		}


	}
</style>